繁体   English   中英

我可以不实例化模板类而显式实例化模板类的模板成员吗?

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

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

//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 :: print可以根据对模板自由函数的调用来编写。

这样,您可以实现成员函数的部分专业化的效果。

这里的主要问题是“ 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)

暂无
暂无

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

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