For a template class:
template <typename T>
struct X
{
static void f(){...}
};
Is there any way to prevent this class from being instantialized for
different T?
e.g:
X<int>::f();
X<int>::f() //ok
///////////////////////////////////////////////
X<int>::f();
X<double>::f() //compiling error
Instantialization may be found in different source files, and X<T> may
not have to have any instance.
I tried some methods, but failed to prevent it in compile time.
Can anyone help me out?
(1)
On 12 Mrz., 15:19, "shifan3" <shifan1234...@163.com> wrote:
SFINAE is your friend. Your main task is to define/specialize
your traits class MyTraits, which specifies enablement, properly.
In this case I have used explicit specializiation for it, maybe you
need partial specialization:
template <bool Enable, typename T = void>
struct EnableIf {
typedef T Type;
};
template <typename T>
struct EnableIf<false, T> {
};
template <typename T>
struct MyTraits {
static const bool value = false; // Default case: Disable
};
template <>
struct MyTraits<int> {
static const bool value = true;
};
template <typename T>
struct X
{
static typename
EnableIf<MyTraits<T>::value>::Type f(){...}
};
int main() {
X<int>::f(); // OK
X<double>::f(); // Fails
}
Greetings from Bremen,
Daniel Krügler
(2)
template <typename T>
struct X
{
static void f(){...}
};
template<> struct X<double>;
or, if you don't want the incomplete type,
template<>
struct X<double>
{
};
本文探讨了如何在C++中防止模板类对于特定类型的实例化。通过使用SFINAE(子表达式失败不是错误)技术和条件编译,作者展示了如何仅允许某些类型实例化模板类的方法。

被折叠的 条评论
为什么被折叠?



