繁体   English   中英

部分模板特化 c++ 不完整类型的无效使用

[英]Invalid use of incomplete type for partial template specialization c++

我正在尝试专门化一个类方法foo() 这适用于完整的模板专业化。 但是,这不适用于部分模板特化。

这是在 GCC 和 Clang 上编译良好的示例代码:

#include <iostream>
#include <string>

template <typename Key, typename Value>
struct SimpleKey {
    Key   key;
    Value value;
    void foo() const { 
        std::cout << "base" << std::endl; 
    }
};

/*
// Uncomment this and it won't work !
template<typename Key>
void SimpleKey<Key, std::string>::foo() const {
    std::cout << "partial" << std::endl; 
}
*/

template<>
void SimpleKey<int, std::string>::foo() const {
    std::cout << "full" << std::endl; 
}


int main() {
    SimpleKey<double, std::string> key1{1.0,"key1"};
    key1.foo();
    SimpleKey<int, std::string> key2{1,"key2"};
    key2.foo();
}

取消注释相关代码时,我在 Clang 和 GCC 上出现的错误是:

错误:无效使用不完整类型 'struct SimpleKey >' void SimpleKey::foo() const {

我应该怎么做才能使部分模板专业化以“最小”努力正常工作?

您可以显式特化类模板的特定隐式实例化的成员函数。 但这在部分专业化中是不允许的。 如果你不想写一个完整的偏特化,你可以考虑使用标签调度:

private:
void foo(std::true_type /*value_is_string*/) const { /* "partial" */ }
void foo(std::false_type /*value_is_string*/) const { /* "base" */ }

public:
void foo() const { return foo(std::is_same<Value, std::string>()); }

或者将foo()重构为您部分专业化的基类模板。

直接是不可能的。 (很遗憾,这种语法很好)但是您可以执行以下操作:

namespace detail {
    inline void f_(int i) { /* spé for int */}
    inline void f_(long i) { /* spé for long*/}
    /* other spe... */
}

template<class T>
struct Foo{
    void f(T arg) { detail::f_(arg);}
};

它不是那么直接,但它仍然很容易阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM