c++ - 强制模板成员函数实例化

标签 c++ templates c++11 instantiation

我在命名空间 N 中有一个类 C,它有一个公共(public)模板成员函数 F,如下所示:

namespace N {
    class C {
    public:
        template<int I>
        void F() {
            // ...
        }
    };
};

I 的值对于 N::C::F<I>直到运行时才知道。但是,I 的值被限制为 0 <= I < 2^8 .我正在寻找一种方法来强制此函数将模板扩展到所有 256 种可能的形式。

到目前为止,我已经在 C 的第二个函数中手动创建了一个静态数组。指向所有可能的函数:

        template<int I>
        void F() {
            // ...
        }

        void G(int I) {
            static void(* const funcs[256])() = {
                F<0>, F<1>, F<2>, ...
            };

            funcs[I]();
        }

虽然我想知道是否有更好的方法。我已经在 N 中有了一个宏负责为 I 的每个值构造一个单独的结构(供 F 本身使用)并正在寻找我是否可以以某种方式在其中集成模板成员函数的实例化:

    template<int> struct S;

    #define M(I, n) \
        template<> struct S<I> { \
            static const char name[] = #n; \
            /*
                Some how instantiate the function here, like (just guessing here):

                static const SEvaluator<I> eval = &C::F<I>;

                given

                template<int I>
                using SEvaluator = void(*)();
            */
        };

    M(0, "foo"); M(1, "bar");

    #undef M

我提出的方法无法正常工作,编译器提示 F 不是一个 constexpr。 F操作了C的几个变量并调用外部方法并且不能声明为 constexpr。有没有办法挽救这个问题,还是我必须求助于我的第一个 hackish 方法?

最佳答案

您可以使用 index_sequence<I...> (C++14) 并展开 I进入静态数组。

template<std::size_t... Is>
void G(int i, std::index_sequence<Is...>) {
    using C = void(C::*)();
    static C funcs[sizeof...(Is)] = { &C::F<Is>... };
    (this->*funcs[i])();
}

void G(int i) {
    G(i, std::make_index_sequence<256>());
}

对于非 C++14 解决方案,您可以编写自己的 index_sequence 版本:

template<int... Is>
struct index_sequence { };

template<int N, int... Is>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> { };

template<int... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> { };

关于c++ - 强制模板成员函数实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976949/

相关文章:

c++ - 使用 C 读取图像的所有字节并存储在字节数组中

c++ - 功能模板与自动关键字

c++ - 基于范围的 for 循环和 std::vector.push_back() 使程序崩溃

c++ - 使用 const CString& 而不是单独使用 CString 作为函数参数是否有任何性能优势?

c++ - boost::filesystem::path 中的 "/"字符有什么用?

c++ - 如何确保传递给可变参数模板函数的所有容器都具有相同的大小?

c++ - 为什么 std::istream::read 不根据读取的字节移动文件指针

c++ - Unordered_map 到二进制文件

c++ - 我什么时候会在 constexpr 上使用 std::integral_constant?

c++ - STL 代码 typedef typename value_type、size_type 等。这些是如何工作的?