首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:如何使用模板函数中的类型进行分支?

C++:如何使用模板函数中的类型进行分支?
EN

Stack Overflow用户
提问于 2011-06-23 10:17:50
回答 6查看 5.3K关注 0票数 11

我不是很精通模板。如何编写一个名为get的模板函数,该函数根据模板类型选择从中获取的数组?如下例所示:

代码语言:javascript
复制
struct Foo
{
    int iArr[10];
    char cArr[10];

    // How to pick array here based on template type?
    template < typename T >
    T get( int idx )
    {
        // This does NOT work!
        switch ( T )
        {
        case int:
            return iArr[ idx ];
        case char:
            return cArr[ idx ];
        }
    }
};

// Expected behaviour of get()
Foo foo;
int i  = foo.get< int >( 2 );
char c = foo.get< char >( 4 );
EN

回答 6

Stack Overflow用户

发布于 2011-06-23 11:10:49

虽然Jason提出的解决方案有效,但它远不是惯用的,而且更难维护,因为switch语句中的case值没有明显的意义(“魔术数字”),2)很容易与switch_value<>专门化中的值不同步。我建议这样做:

代码语言:javascript
复制
struct Foo {
    Foo() : iArr(), cArr() { }

    template<typename T>
    T get(std::size_t const idx) const     {
        return Foo::get_dispatcher<T>::impl(*this, idx);
    }

private:
    int iArr[10];
    char cArr[10];

    template<typename T>
    struct get_dispatcher;
};

template<>
struct Foo::get_dispatcher<int> {
    static int impl(Foo const& foo, std::size_t const idx) {
        return foo.iArr[idx];
    }
};

template<>
struct Foo::get_dispatcher<char> {
    static char impl(Foo const& foo, std::size_t const idx) {
        return foo.cArr[idx];
    }
};

使用intchar以外的任何类型调用Foo::get<>都会产生编译器错误。

票数 10
EN

Stack Overflow用户

发布于 2011-06-23 10:27:14

您需要添加某种类型的值结构,您可以使用它来获取switch语句的值。例如:

代码语言:javascript
复制
template<typename T>
struct switch_value {};

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

template<>
struct switch_value<char>
{
    enum { value = 2 };
};

//then inside you structure Foo
template <typename T>
T get( int idx )
{
    switch ( switch_value<T>::value )
    {
    case 1:
        return iArr[ idx ];
    case 2:
        return cArr[ idx ];
    }
}

这里的好处是,如果您使用的类型没有有效值,这将抛出一个编译器错误,因为switch_value<T>的默认版本没有定义成员value,所以如果您没有为特定类型指定结构,那么这样的模板实例化将失败。

票数 9
EN

Stack Overflow用户

发布于 2013-07-31 02:23:41

所有这些答案都太夸张了。

代码语言:javascript
复制
template <typename T>
T get( int idx )
{
   if ( boost::is_same<T, int>::value)
      return *(T*)&iArr[ idx ];
   else
      return *(T*)&cArr[ idx ];
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6448653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档