【问题标题】:Template specialization behavior example模板特化行为示例
【发布时间】:2015-08-11 01:13:05
【问题描述】:

我正在尝试了解 C++ 中的模板专业化。我已阅读其他论坛,但无法使其在实践中发挥作用。我正在尝试通过一个非常简单的示例来学习,我将对此进行解释。

我想要实现的目标:我希望 foo 根据类型表现出不同的行为。下面的代码不起作用,但我已经评论了我想看到的行为。有人可以填写我评论的行。 如果有什么不清楚的地方请告诉我。

#include <iostream>
#include <string>

template <typename T>
class my_template 
{
public:
    foo() {return 0} // default behavior if there does not exist foo() function for the specified type 
};

template <>
class my_template<int> 
{
public:
    // implement foo function: should return -1 if the type = int 
};

template <>
class my_template<long>
{
public:
    // implement foo function: should return 100 if the type = long 
};

int main() 
{
    my_template<int> x;
    my_template<long> y;
    my_template<double> z;
    std::cout << x.foo() << "\n"; // print -1 
    std::cout << y.foo() << "\n"; // print 100 
    std::cout << z.foo() << "\n"; // print 0
    return 0;
}

【问题讨论】:

  • @Jarod42 - 抱歉,我不知道有什么区别。我将更新标题并进行少量编辑。不过我的问题应该还是很清楚的。
  • polymorphim 是拼写错误...缺少一个“s”。
  • foo inside my_template 也不应该像你拥有的那样编译(没有返回类型)
  • @Jarod42 - 模板特化是否被认为是多态行为?

标签: c++ generics polymorphism


【解决方案1】:

只是向您展示几种不同的方法。

如果你使用元函数方法,那么在运行时什么都不会做(保证):

template<typename>
struct my_template{
    enum { value = 0 };
};

template<>
struct my_template<int>{
    enum { value = -1 };
};

template<>
struct my_template<long>{
    enum { value = 100 };
};

int main(){
    std::cout << "float:  " << my_template<float>::value << '\n';
    std::cout << "int:    " << my_template<int>::value << '\n';
    std::cout << "long:   " << my_template<long>::value << '\n'; 
}

或者您可以使用模板变量 (C++14):

template<typename>
constexpr int my_value = 0;

template<>
constexpr int my_value<int> = -1;

template<>
constexpr int my_value<long> = 100;

int main(){
    std::cout << "float:  " << my_value<float> << '\n';
    std::cout << "int:    " << my_value<int> << '\n';
    std::cout << "long:   " << my_value<long> << '\n';
}

或者使用模板函数:

template<typename T> 
int func_impl(T){ return 0; }
int func_impl(int){ return -1; }
int func_impl(long){ return 100; }

template<typename T>
int func(){
    return func_impl(T(0));
}

int main(){
    std::cout << "float:  " << func<float>() << '\n';
    std::cout << "int:    " << func<int>() << '\n';
    std::cout << "long:   " << func<long>() << '\n';
}

【讨论】:

  • 你的第二个例子不会为我编译,它给 constexpr 带来了问题
  • @Ryan 你用的是什么编译器? it works fine with gcc
  • @Ryan microsoft 在跟上标准方面是出了名的差。
【解决方案2】:
template <typename T>
class my_template 
{
public:
  int foo() {return 0;} // default behavior 
};

template <>
class my_template<int> 
{
public:
  int foo() {return -1;}
};

够了吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多