0

如果我有一个模板类MyClass<T>,并且如果我显式地实例化intand float(在cpp文件中),那么我可以使用extern template class MyClass<int>andextern template class MyClass<float>来防止遇到此类的任何编译单元不必要地实例int化它。float当然,对于任何其他类型,该类仍将被实例化。

现在我有一个类MyClass2<T>,它只适用于int, float, char,doubleshort它们的无符号变体(如果适用)。由于我事先知道所有类型,因此该类中所有方法的定义都在cpp文件中。这也是我MyClass2<T>为所有上述类型显式实例化的地方。在标题中,我static_assert阻止用户MyClass2<T>使用不受支持的类型创建。

有什么方法可以完全防止MyClass2<T>实例化extern template class MyClass2;所有类型(例如,尽管我知道这不起作用),包括支持的类型?想一网打尽?_ extern template我想避免输入extern template class MyClass2<int>所有支持的类型。

考虑到我已经为这些类型显式实例化了类,这似乎不仅是多余的,而且对于大型项目(比如我正在处理的项目)来说,每次添加新类型时我还需要维护另外几行代码。

4

3 回答 3

1

老实说,这听起来像是宏的工作:

// explicit_instantiations.h
#ifndef PERFORM_INSTANTIANTION
#define EXTERNALLY_INSTANTIATED extern
#else
#define EXTERNALLY_INSTANTIATED
#endif

EXTERNALLY_INSTANTIATED template class MyClass<int>;
EXTERNALLY_INSTANTIATED template class MyClass<float>;
// etc.

// header
#include "explicit_instantiations.h"

// cpp file
#define PERFORM_INSTANTIATION
#include "explicit_instantiations.h"
于 2014-10-28T15:46:51.090 回答
1

您可以使用 SFINAE 如下

template<typename T>
using value_type =  typename std::enable_if<
                    std::is_same<float, T>::value ||
                    std::is_same<double, T>::value
                    //...other supported types goes here
                   >::type  ;



template<class T, class Enable = void>
class  MyClass2 ;

template<class T>
class MyClass2<T, value_type<T> > 
{
};

 MyClass2<float> t;
 MyClass2<int> t1; // Error !

Here

于 2014-10-26T13:32:31.607 回答
0

关于什么:

template <typename T>
struct Base {};

template <typename T> 
struct Supported;

template <> 
struct Supported<int> : public Base<int>
{};
于 2014-10-26T13:12:28.017 回答