Title: How to limit instantialization?
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>
{
};