c – 具有不同签名的类方法专业化

c – 具有不同签名的类方法专业化,第1张

概述我正在尝试编写一个类模板,其中方法签名会根据模板参数而改变.我的目标是尽可能少地复制代码.考虑这个例子,首先是类声明: // a.hxx#ifndef A_HXX#define A_HXXtemplate<typename T>struct A{ void foo(T value) const; void bar() const;};#include <strin 我正在尝试编写一个类模板,其中方法签名会根据模板参数而改变.我的目标是尽可能少地复制代码.考虑这个例子,首先是类声明:

// a.hxx#ifndef A_HXX#define A_HXXtemplate<typename T>struct A{    voID foo(T value) const;    voID bar() const;};#include <string>#ifndef short_declarationtemplate<>struct A<std::string>{    voID foo(const std::string &value) const;    voID bar() const;};#else // short_declarationtemplate<>struct A<std::string>{    voID foo(const std::string &value) const;};#endif // short_declaration#endif // A_HXX

现在类定义:

// a_impl.hxx#ifndef A_IMPL_HXX#define A_IMPL_HXX#include "a.hxx"#include <iostream>#include <typeinfo>template<typename T>voID A<T>::foo(T value) const{    std::cout << "A<T=" << typeID(T).name() << ">::foo(" << value << ")"        << std::endl;}template<typename T>voID A<T>::bar() const{    std::cout << "A<T=" << typeID(T).name() << ">::bar()" << std::endl;}voID A<std::string>::foo(const std::string &value) const{    std::cout << "A<std::string>::foo(" << value << ")" << std::endl;}#ifndef skip_duplicatesvoID A<std::string>::bar() const{    std::cout << "A<std::string>::bar()" << std::endl;}#endif // skip_duplicates#endif // A_IMPL_HXX

现在是一个测试程序:

// test.cxx//#define skip_duplicates//#define short_declaration#include "a_impl.hxx"int main(voID){    A<int>         obj1;    A<std::string> obj2;    int         value1(1);    std::string value2("baz");    obj1.foo(value1);    obj1.bar();    obj2.foo(value2);    obj2.bar();    return 0;}

如果像这样编译,我得到的预期输出(对于我的typeID实现):

A<T=i>::foo(1)A<T=i>::bar()A<std::string>::foo(baz)A<std::string>::bar()

但我当然喜欢在我的例子中启用skip_duplicates甚至short_declaration的方法.有点similar question,ecatmur回复说需要给出完整的类,所以至少定义short_declaration是行不通的.

其他人如何使用可能将大对象作为参数的方法来处理创建类模板的问题?

解决方法 您可以将重复项提取到基类中:

template<typename T>struct Base{    voID bar()    {        std::cout << "A<T=" << typeID(T).name() << ">::bar()" << std::endl;    }protected:    ~Base(){}    template<typename U>    voID DoFoo(U value)    {        std::cout << "A<T=" << typeID(T).name() << ">::foo(" << value << ")"        << std::endl;    }};template<typename T>struct A : Base<T> {    voID Foo(T value)    {        DoFoo(value);    }};template<>struct A<std::string> : Base<std::string> {    voID Foo(const std::string& value)    {        DoFoo(value);    }};
总结

以上是内存溢出为你收集整理的c – 具有不同签名的类方法专业化全部内容,希望文章能够帮你解决c – 具有不同签名的类方法专业化所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1230721.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存