我可以在不实例化模板类的情况下显式实例化模板类的模板成员吗?

Can I explicitly instantiate template member of template class without instantiating the template class?

本文关键字:实例化 成员 情况下 我可以      更新时间:2023-10-16

我想显式实例化模板成员,但不实例化模板类。但是我收到编译器错误,所以这可能吗?这是我的代码:

//mytemplate.h
template <class T>
class mytemplate
{
 public:
  mytemplate(T* tt)
  {
     mT = tt;
  }
  template<class B>
  void print(const B& bb); 
  T* mT;
};
//in mytemplate.cpp
#include "mytemplate.h"
template<typename T>
template<typename B>
void mytemplate<T>:: print(const B& bb)
{
   B b = bb;
}
template<typename T> void  mytemplate<T>::print<float>(const float&) const;
template<typename T> void    mytemplate<T>::print<int>(const int&) const;
// main.cpp
int main()
{
  int d =0;
  mytemplate<int> k(&d);
  k.print<float>(4.0);
}

使用模板,将问题分解为尽可能小的构建块总是有帮助的。 MyTemplate::p RINT可以通过调用模板自由函数来编写。

通过这种方式,您可以实现成员函数的部分专用化效果。

这里一个主要问题是"print(( 方法应该做什么?下面是一个示例,其中mytemplate<T>为免费函数提供打印策略。当然,没有理由说该策略不可能是通过其他一些(可能是专门的(模板自由函数构建的其他类。

// Policy is a concept which supports 2 methods:
// print_prefix() and print_postfix()
//
template<class Policy, class B>
void print_with_policy(const Policy& policy, const B& value) const
{
  policy.print_prefix();
  cout << value;
  policy.print_postifx();
}
template<class T>
struct mytemplate
{
  // implement in terms of a free function
  template<class B> void print(const B& value) {
    print_with_policy(*this, value);
  }
  // policy concept implementation
  void print_prefix() const {
    cout << "prefix-";
  }
  void print_postfix() const {
    cout << "-postfix";
  }
};

扩展示例以使用具有字符串专用的单独策略类:

template<typename B>
struct default_policy {
    default_policy(const B& value) : _value(value) {}
    void operator()() const {
        cout << "(" << _value << ")";
    }
private:
    const B& _value;
};
template<typename B>
struct quoted_policy {
    quoted_policy(const B& value) : _value(value) {}
    void operator()() const {
        cout << '"' << _value << '"';
    }
private:
    const B& _value;
};
template<class B>
default_policy<B> make_policy(const B& value) {
    return default_policy<B>(value);
}
// overload for B being a string
quoted_policy<std::string> make_policy(const std::string& value) {
    return quoted_policy<std::string>(value);
}
template<class T>
struct mytemplate
{
    // implement in terms of a free function
    template<class B> void print(const B& value) {
        make_policy(value)();
        cout << endl;
    }
};
int main()
{
    struct foo{};
    mytemplate<foo> fooplate;
    fooplate.print(int(8));
    fooplate.print(std::string { "a string" });
    fooplate.print("not a string");

    return 0;
}

输出:

(8)
"a string"
(not a string)