【问题标题】:Is it possible to prevent a C++ template being used without specialization?是否可以防止在没有专门化的情况下使用 C++ 模板?
【发布时间】:2012-09-11 02:42:10
【问题描述】:

是否可以防止在没有专门化的情况下使用 C++ 模板?

例如,我有

template<class T>
void foo() {}

而且我不希望它在没有专门用于 foo&lt;int&gt;foo&lt;char&gt; 的情况下被使用。

【问题讨论】:

标签: c++ templates template-specialization


【解决方案1】:

您应该能够声明该函数,而无需在通用情况下实际定义它。这将导致对非专业模板的引用发出未定义符号链接器错误。

template<class T>
void foo();

template<>
void foo<int>() {
    // do something here
}

clang++ 对我来说效果很好。

【讨论】:

    【解决方案2】:

    您可以在函数体中使用未定义的类型。你会得到compile time错误信息:

    template<class T> struct A;  
    template<class T>  
    void foo()  
    {  
       typename A<T>::type a;  // template being used without specialization!!!
       cout << "foo()\n";  
    }  
    template<>  
    void foo<int>()  
    {  
       cout << "foo<int>\n";  
    }  
    template<>  
    void foo<char>()  
    {  
       cout << "foo<char>\n";  
    }  
    int main()  
    {  
      foo<int>();  
      foo<char>();  
    //  foo<double>();   //uncomment and see compilation error!!!
    }  
    

    【讨论】:

      【解决方案3】:

      当 foo 函数有参数时是可能的。 例如:模板 void foo(T param){} 现在,你可以调用 foo(1), foo('c') 而无需专门化。

      【讨论】:

        猜你喜欢
        • 2022-06-14
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        相关资源
        最近更新 更多