c++ - 模板特化子类

标签 c++ c++11 templates inheritance

我有一个问题可以最小化为以下示例

#include <iostream>
#include <string>


class A{
  public:
    const char* chr;
    A(){chr = "aaa";}
};

class B : A{
  public:
    const char* chr;
    B(){chr = "bbb";}
};

template <class T>
std::string to_str(T) = delete;

template<>
inline std::string
to_str<A>(A object) {
    std::string str;
    return str.assign((object.chr));
}

int main() {
  A a;
  B b;
  std::cout << to_str(b) << std::endl;
}

将其更改为 std::cout << to_str(a) << std::endl; 时代码运行并打印'aaa ',但是像这样,它在编译和输出时停止

main.cpp: In function 'int main()':
main.cpp:30:24: error: use of deleted function 'std::__cxx11::string to_str(T) [with T = B; std::__cxx11::string = std::__cxx11::basic_string<char>]'
   std::cout << to_str(b) << std::endl;
                        ^
main.cpp:18:13: note: declared here
 std::string to_str(T) = delete;
             ^~~~~~

exit status 1

现在假设我有很多类继承 A ,我可以“告诉”编译器它们都可以转到相同的函数(接受 A 的函数)吗?

谢谢。

最佳答案

can i 'tell' the compiler they all can go to the same function(the one accepts A)?

是的,使用 SFINAE 和 std::is_base_of

template <typename T>
typename std::enable_if<std::is_base_of<A, T>::value, std::string>::type
      to_str (T const & t)
 { return t.chr; }

下面是一个完整的工作示例

#include <type_traits>
#include <iostream>
#include <string>

struct A     { char const * chr; A() : chr{"aaa"} {} };
struct B : A { char const * chr; B() : chr{"bbb"} {} };
struct C     { char const * chr; C() : chr{"ccc"} {} };    

template <typename T>
typename std::enable_if<std::is_base_of<A, T>::value, std::string>::type
      to_str (T const & t)
 { return t.chr; }

int main()
 {
   A a;
   B b;
   C c;

   std::cout << to_str(a) << std::endl;    // print aaa
   std::cout << to_str(b) << std::endl;    // print bbb
   // std::cout << to_str(c) << std::endl; // compilation error
 }

关于c++ - 模板特化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46320222/

相关文章:

c++ - C++如何在同一行中cin和cout?

c++ - gdb 将稳定的时钟值转换为实际时间

c++ - 为什么用作嵌套成员的非模板类是不完整类型?

c++ - 具有未定义成员函数返回类型的模板实例化

jquery - 如何使用 jQuery mobile 通过 AJAX 加载多页模板?

C++在范围内生成(xyz)点

c++ - 如何在 C++ 中使用/创建 unique_lock?

c++ - GSL 编译错误

c++ - std::move 在 boost 库中的对应物

c++ - 在 C++11 中实现线程安全方法的正确方法