c++ - 模板偏特化和从属名称

标签 c++ templates types partial-specialization

考虑以下

#include <iostream>

template <typename T, bool B>
struct C {
    using value_type = T;

    value_type f(value_type v);
};

template <bool B>
auto C<int, B>::f(value_type v) -> value_type {
    return v;
}

int main(int argc, char * argv[]) {
    C<int, true> c;
    std::cout << c.f(5) << std::endl;
    return 0;
}

使用 g++ 4.9 我得到错误

test.cpp:11:26: error: 'C::f' declared as an 'inline' variable
inline auto C::f(value_type v) -> value_type {
test.cpp:11:26: error: template definition of non-template 'auto C::f'
test.cpp:11:26: error: 'value_type' was not declared in this scope

问题出在 value_type .当我用 typename C<int, B>::value_type 替换它时它会起作用但这要长得多,特别是在现实世界的应用程序中,它可能会很长(我的情况)。有没有办法使它与短变体一起工作?

PS:它适用于完整的模板特化,但我只需要部分特化。

最佳答案

当您使用模板时,实际上您是在定义一种新类型,即使是针对模板特化也是如此。

因此,让您的程序正常运行的正确方法是完全重新定义特化。

#include <iostream>

template <typename T, bool B>
struct C {
    T f(T v);
};

template <bool B>
struct C<int,B> {
  int f(int v) {
    return v;
  }
};

int main(int argc, char * argv[]) {
    C<int, true> c;
    std::cout << c.f(5) << std::endl;
    return 0;
}

关于c++ - 模板偏特化和从属名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221015/

相关文章:

c# - 如何在 ObservableCollection 中捕获通用对象的类型?

jquery - jQuery ajax 接受 attrib 有什么意义?它实际上有什么作用吗?

用于获取 nothrow 运算符 new 地址的 C++ 语法

c++ - 为什么用()声明对象时不调用构造函数?

c++ - 无限递归 C++

C++ 模板变量代码效率

c++ - 根据下面的作者,如果两个指针指向不同的数组,比较的第一个版本将是未定义的

PHP:函数中的函数然后包含在内部函数中

c++ - 为什么 sizeof... 不能使用这个别名模板?

java - 泛型类中私有(private)迭代器出现奇怪的输入错误