【问题标题】:Specify template parameters at runtime在运行时指定模板参数
【发布时间】:2010-05-20 12:48:53
【问题描述】:

考虑以下模板类

class MyClassInterface {
public:
  virtual double foo(double) = 0;
}

class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
  double foo(double a) {
    // complex computation dependent on P1, P2, P3
  }
  // more methods and fields (dependent on P1, P2, P3)
}

模板参数P1、P2、P3 处于受限范围内,例如从0 到某个固定值n 在编译时固定。

现在我想构建一个“工厂”方法,例如

MyClassInterface* Factor(int p1, int p2, int p3) {
  return new MyClass<p1,p2,p3>(); // <- how to do this?
}

问题是在模板参数只在运行时知道的情况下,如何实现模板类的构造。对于具有非常大域(如双精度)的模板参数,是否也可以这样做?另请考虑,如果可能的解决方案可扩展为使用更多模板参数。

【问题讨论】:

  • 我真的很想知道这个问题之外的原因。您能否向我们解释一下您通过使用这种奇怪的结构想要达到什么目的?
  • 有一个庞大的算法可以使用模板整数参数进行参数化。根据参数,编译会生成一些高度优化的代码。现在,我希望能够从外部使用这些不同的“版本”,而无需关心它们的实现,并通过在运行时以用户监督的方式指定参数。尽管有这个应用程序,但出于纯粹的好奇,这也是一个理论问题。
  • 请注意,由于可能有大量特化的实例化,由此产生的巨大可执行文件大小在技术上可能不利于您的优化性能。大代码通常意味着慢代码,尤其是在存在不规则分支模式的情况下。 (一如既往,配置文件以了解发生了什么)

标签: c++ templates


【解决方案1】:

您可以这样做:

MyClassInterface* Factor(int p1, int p2, int p3) {
  if (p1 == 0 && p2 == 0 && p3 == 0)
    return new MyClass<0,0,0>();
  if (p1 == 0 && p2 == 0 && p3 == 1)
    return new MyClass<0,0,1>();
  etc;
}

请注意,这甚至不能远程缩放到浮点值。它仅缩放到已知的离散值列表。


我之前也用过这段代码来做一些模板自动生成:

#include <boost/preprocessor.hpp>

#define RANGE ((0)(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12))
#define MACRO(r, p) \
    if (BOOST_PP_SEQ_ELEM(0, p) == var1 && BOOST_PP_SEQ_ELEM(1, p) == var2 && BOOST_PP_SEQ_ELEM(2, p) == var3 && BOOST_PP_SEQ_ELEM(3, p) == var4) \
        actual_foo = foo<BOOST_PP_TUPLE_REM_CTOR(4, BOOST_PP_SEQ_TO_TUPLE(p))>;
BOOST_PP_SEQ_FOR_EACH_PRODUCT(MACRO, RANGE RANGE RANGE RANGE)
#undef MACRO
#undef RANGE

编译器生成如下所示的输出:

if (0 == var1 && 0 == var2 && 0 == var3 && 0 == var4) actual_foo = foo<0, 0, 0, 0>;
if (0 == var1 && 0 == var2 && 0 == var3 && 1 == var4) actual_foo = foo<0, 0, 0, 1>;
if (0 == var1 && 0 == var2 && 0 == var3 && 2 == var4) actual_foo = foo<0, 0, 0, 2>;
if (0 == var1 && 0 == var2 && 0 == var3 && 3 == var4) actual_foo = foo<0, 0, 0, 3>;
if (0 == var1 && 0 == var2 && 0 == var3 && 4 == var4) actual_foo = foo<0, 0, 0, 4>; 
if (0 == var1 && 0 == var2 && 0 == var3 && 5 == var4) actual_foo = foo<0, 0, 0, 5>;
if (0 == var1 && 0 == var2 && 0 == var3 && 6 == var4) actual_foo = foo<0, 0, 0, 6>;
if (0 == var1 && 0 == var2 && 0 == var3 && 7 == var4) actual_foo = foo<0, 0, 0, 7>;
if (0 == var1 && 0 == var2 && 0 == var3 && 8 == var4) actual_foo = foo<0, 0, 0, 8>;
etc...

另外,请注意,使用此方法时,有 4 个变量,每个变量的范围超过 13 个值,您将导致编译器实例化此函数的 28561 个副本。如果您的 n 为 50,并且您仍然有 4 个选项,那么您将实例化 6250000 个函数。这可能会导致编译缓慢。

【讨论】:

  • '这可能会导致编译缓慢' - 更不用说接近半 GB 的预处理大小和产生的巨大可执行文件大小,如果你找到了可以处理的编译器的话。
  • @Joe:当然。我已经将它用于一组我想尝试模板化的布尔值。我认为我做过的最多的是
  • 为什么不使用BOOST_PP_SEQ_ENUM_PARAMS 而不是转换为元组并删除构造函数?有效率原因吗?
  • @Matthieu:宏生成的效率并不是真正的问题。我从来没有使用过超过一天的代码,所以它只是被一起破解了。唯一的其他评论是我使用的是 Boost 1.33.1,它可能支持也可能不支持一些额外的宏调用。
  • 编译速度慢,并且由于代码大小和指令缓存未命中,运行时间可能很慢,首先破坏了进行编译时微优化的意义。这似乎很重要,需要注意。
【解决方案2】:

如果你不喜欢宏,那么你也可以使用模板生成 if-then-else:

#include <stdexcept>
#include <iostream>

const unsigned int END_VAL = 10;

class MyClassInterface
{
public:
    virtual double foo (double) = 0;
};

template<int P1, int P2, int P3>
class MyClass : public MyClassInterface
{
public:
    double foo (double a)
    {
        return P1 * 100 + P2 * 10 + P3 + a;
    }
};

struct ThrowError
{
    static inline MyClassInterface* create (int c1, int c2, int c3)
    {
        throw std::runtime_error ("Could not create MyClass");
    }
};

template<int DEPTH = 0, int N1 = 0, int N2 = 0, int N3 = 0>
struct Factory : ThrowError {};

template<int N2, int N3>
struct Factory<0, END_VAL, N2, N3> : ThrowError {};

template<int N1, int N3>
struct Factory<1, N1, END_VAL, N3> : ThrowError {};

template<int N1, int N2>
struct Factory<2, N1, N2, END_VAL> : ThrowError {};

template<int N1, int N2, int N3>
struct Factory<0, N1, N2, N3>
{
    static inline MyClassInterface* create (int c1, int c2, int c3)
    {
        if (c1 == N1)
            return Factory<1, N1, 0, 0>::create (c1, c2, c3);
        else
            return Factory<0, N1 + 1, N2, N3>::create (c1, c2, c3);
    }
};

template<int N1, int N2, int N3>
struct Factory<1, N1, N2, N3>
{
    static inline MyClassInterface* create (int c1, int c2, int c3)
    {
        if (c2 == N2)
            return Factory<2, N1, N2, 0>::create (c1, c2, c3);
        else
            return Factory<1, N1, N2 + 1, N3>::create (c1, c2, c3);
    }
};

template<int N1, int N2, int N3>
struct Factory<2, N1, N2, N3>
{
    static inline MyClassInterface* create (int c1, int c2, int c3)
    {
        if (c3 == N3)
            return new MyClass<N1, N2, N3> ();
        else
            return Factory<2, N1, N2, N3 + 1>::create (c1, c2, c3);
    }
};

MyClassInterface* factory (int c1, int c2, int c3)
{
    return Factory<>::create (c1, c2, c3);
}

由于测试是嵌套的,它应该比 sharth 的宏解决方案更有效。

您可以通过添加更多深度案例将其扩展到更多参数。

【讨论】:

    【解决方案3】:

    这是不可能的,模板是在编译时实例化的。
    当您拥有可执行文件时,您只有类(这些模板的特定实例化),不再有模板。

    如果您在编译时不知道值,您就无法为这些值提供模板。

    【讨论】:

    • 这不是真的。对于具有小域的整数参数,可以使用 switch/if 语句,如 sharth 的帖子中所述。
    • 如果不构建所有可能的情况并进行运行时切换,就无法achieve the construction of the template class when template parameters are only known at runtime。
    • 问题是如何进行这种递归切换(无需手动将其写成代码)。
    【解决方案4】:

    我不知道这是否适用于您当前的问题,但似乎 C++11 constexpr 可能就是你要找的东西 - constexpr 函数可以在运行时调用,同时也可以在编译时执行。

    使用constexpr 还具有比使用 TMP 看起来更“干净”的额外好处,可以处理任何运行时值(不仅仅是整数值),同时保留 TMP 的大部分优点,例如记忆和编译时执行,尽管这在某种程度上是由编译器决定的。事实上,constexpr 通常比 TMP 等效版本快得多。

    还要注意,一般来说,在运行时使用模板会破坏模板最大的特性之一——它们在编译时被处理并且在运行时几乎消失。

    【讨论】:

    • 请举例?
    【解决方案5】:

    这在技术上是*可能的** - 但它不实用,而且几乎可以肯定这是解决问题的错误方法。

    P1、P2、P3不能是正则整数变量有什么原因吗?


    *您可以嵌入一个 C++ 编译器和您的源代码的副本,然后编译一个动态库或共享对象,为给定的一组 P1、P2、P3 实现您的工厂函数 - 但您真的想这样做吗? IMO,这绝对是一件疯狂的事情。

    【讨论】:

      【解决方案6】:

      你不能。模板只是编译时间。

      您可以在编译时构建您想要的所有可能的模板值,并在运行时选择其中一个。

      【讨论】:

        【解决方案7】:

        太晚了,我知道,但是这个呢:

        // MSVC++ 2010 SP1 x86
        // boost 1.53
        
        #include <tuple>
        #include <memory>
        // test
        #include <iostream>
        
        #include <boost/assert.hpp>
        #include <boost/static_assert.hpp>
        #include <boost/mpl/size.hpp>
        #include <boost/mpl/vector.hpp>
        #include <boost/mpl/push_back.hpp>
        #include <boost/mpl/pair.hpp>
        #include <boost/mpl/begin.hpp>
        #include <boost/mpl/deref.hpp>
        #include <boost/mpl/int.hpp>
        #include <boost/mpl/placeholders.hpp>
        #include <boost/mpl/unpack_args.hpp>
        #include <boost/mpl/apply.hpp>
        // test
        #include <boost/range/algorithm/for_each.hpp>
        
        /*! \internal
         */
        namespace detail
        {
        /*! \internal
         */
        namespace runtime_template
        {
        
        /*! \internal
            fwd
         */
        template <
            typename Template
            , typename Types
            , typename Map  // top level map iterator
            , typename LastMap  // top level map iterator
            , int Index
            , bool Done = std::is_same<Map, LastMap>::value
        >
        struct apply_recursive_t;
        
        /*! \internal
            fwd
         */
        template <
            typename Template
            , typename Types
            , typename Map  // top level map iterator
            , typename LastMap  // top level map iterator
            , typename First
            , typename Last
            , int Index
            , bool Enable = !std::is_same<First, Last>::value
        >
        struct apply_mapping_recursive_t;
        
        /*! \internal
            run time compare key values + compile time push_back on \a Types
         */
        template <
            typename Template
            , typename Types
            , typename Map  // top level map iterator
            , typename LastMap  // top level map iterator
            , typename First
            , typename Last
            , int Index // current argument
            , bool Enable /* = !std::is_same<First, Last>::value */
        >
        struct apply_mapping_recursive_t
        {
            typedef void result_type;
            template <typename TypeIds, typename T>
            inline static void apply(const TypeIds& typeIds, T&& t)
            {   namespace mpl = boost::mpl;
                typedef typename mpl::deref<First>::type key_value_pair;
                typedef typename mpl::first<key_value_pair>::type typeId;   // mpl::int
                if (typeId::value == std::get<Index>(typeIds))
                {
                    apply_recursive_t<
                        Template
                        , typename mpl::push_back<
                            Types
                            , typename mpl::second<key_value_pair>::type
                        >::type
                        , typename mpl::next<Map>::type
                        , LastMap
                        , Index + 1
                    >::apply(typeIds, std::forward<T>(t));
                }
                else
                {
                    apply_mapping_recursive_t<
                        Template
                        , Types
                        , Map
                        , LastMap
                        , typename mpl::next<First>::type
                        , Last
                        , Index
                    >::apply(typeIds, std::forward<T>(t));
                }
            }
        };
        
        /*! \internal
            mapping not found
            \note should never be invoked, but must compile
         */
        template <
            typename Template
            , typename Types
            , typename Map  // top level map iterator
            , typename LastMap  // top level map iterator
            , typename First
            , typename Last
            , int Index
        >
        struct apply_mapping_recursive_t<
            Template
            , Types
            , Map
            , LastMap
            , First
            , Last
            , Index
            , false
        >
        {
            typedef void result_type;
            template <typename TypeIds, typename T>
            inline static void apply(const TypeIds& /* typeIds */, T&& /* t */)
            {
                BOOST_ASSERT(false);
            }
        };
        
        /*! \internal
            push_back on \a Types template types recursively
         */
        template <
            typename Template
            , typename Types
            , typename Map  // top level map iterator
            , typename LastMap  // top level map iterator
            , int Index
            , bool Done /* = std::is_same<Map, LastMap>::value */
        >
        struct apply_recursive_t
        {
            typedef void result_type;
            template <typename TypeIds, typename T>
            inline static void apply(const TypeIds& typeIds, T&& t)
            {   namespace mpl = boost::mpl;
                typedef typename mpl::deref<Map>::type Mapping; // [key;type] pair vector
                apply_mapping_recursive_t<
                    Template
                    , Types
                    , Map
                    , LastMap
                    , typename mpl::begin<Mapping>::type
                    , typename mpl::end<Mapping>::type
                    , Index
                >::apply(typeIds, std::forward<T>(t));
            }
        };
        
        /*! \internal
            done! replace mpl placeholders of \a Template with the now complete \a Types
            and invoke result
         */
        template <
            typename Template
            , typename Types
            , typename Map
            , typename LastMap
            , int Index
        >
        struct apply_recursive_t<
            Template
            , Types
            , Map
            , LastMap
            , Index
            , true
        >
        {
            typedef void result_type;
            template <typename TypeIds, typename T>
            inline static void apply(const TypeIds& /* typeIds */, T&& t)
            {   namespace mpl = boost::mpl;
                typename mpl::apply<
                    mpl::unpack_args<Template>
                    , Types
                >::type()(std::forward<T>(t));
            }
        };
        
        /*! \internal
            helper functor to be used with invoke_runtime_template()
            \note cool: mpl::apply works with nested placeholders types!
         */
        template <typename Template>
        struct make_runtime_template_t
        {
            typedef void result_type;
            template <typename Base>
            inline void operator()(std::unique_ptr<Base>* base) const
            {
                base->reset(new Template());
            }
        };
        
        }   // namespace runtime_template
        }   // namespace detail
        
        /*! \brief runtime template parameter selection
        
            \param Template functor<_, ...> placeholder expression
            \param Maps mpl::vector<mpl::vector<mpl::pair<int, type>, ...>, ...>
            \param Types std::tuple<int, ...> type ids
            \param T functor argument type
        
            \note all permutations must be compilable (they will be compiled of course)
            \note compile time: O(n!) run time: O(n)
        
            \sa invoke_runtime_template()
            \author slow
         */
        template <
            typename Template
            , typename Map
            , typename Types
            , typename T
        >
        inline void invoke_runtime_template(const Types& types, T&& t)
        {   namespace mpl = boost::mpl;
            BOOST_STATIC_ASSERT(mpl::size<Map>::value == std::tuple_size<Types>::value);
            detail::runtime_template::apply_recursive_t<
                Template
                , mpl::vector<>
                , typename mpl::begin<Map>::type
                , typename mpl::end<Map>::type
                , 0
            >::apply(types, std::forward<T>(t));
        }
        
        /*! \sa invoke_runtime_template()
         */
        template <
            typename Template
            , typename Map
            , typename Base
            , typename Types
        >
        inline void make_runtime_template(const Types& types, std::unique_ptr<Base>* base)
        {
            invoke_runtime_template<
                detail::runtime_template::make_runtime_template_t<Template>
                , Map
            >(types, base);
        }
        
        /*! \overload
         */
        template <
            typename Base
            , typename Template
            , typename Map
            , typename Types
        >
        inline std::unique_ptr<Base> make_runtime_template(const Types& types)
        {
            std::unique_ptr<Base> result;
        
            make_runtime_template<Template, Map>(types, &result);
            return result;
        }
        
        ////////////////////////////////////////////////////////////////////////////////
        
        namespace mpl = boost::mpl;
        using mpl::_;
        
        class MyClassInterface {
        public:
            virtual ~MyClassInterface() {}
            virtual double foo(double) = 0;
        };
        
        template <int P1, int P2, int P3>
        class MyClass
        : public MyClassInterface {
        public:
            double foo(double /*a*/) {
                // complex computation dependent on P1, P2, P3
                std::wcout << typeid(MyClass<P1, P2, P3>).name() << std::endl;
                return 42.0;
            }
            // more methods and fields (dependent on P1, P2, P3)
        };
        
        // wrapper for transforming types (mpl::int) to values
        template <typename P1, typename P2, typename P3>
        struct MyFactory
        {
            inline void operator()(std::unique_ptr<MyClassInterface>* result) const
            {
                result->reset(new MyClass<P1::value, P2::value, P3::value>());
            }
        };
        
        template <int I>
        struct MyConstant
            : boost::mpl::pair<
                boost::mpl::int_<I>
                , boost::mpl::int_<I>
            > {};
        
        std::unique_ptr<MyClassInterface> Factor(const std::tuple<int, int, int>& constants) {
            typedef mpl::vector<
                MyConstant<0>
                , MyConstant<1>
                , MyConstant<2>
                , MyConstant<3>
                // ...
            > MyRange;
            std::unique_ptr<MyClassInterface> result;
            invoke_runtime_template<
                MyFactory<_, _, _>
                , mpl::vector<MyRange, MyRange, MyRange>
            >(constants, &result);
            return result;
        }
        
        int main(int /*argc*/, char* /*argv*/[])
        {
            typedef std::tuple<int, int, int> Tuple;
            const Tuple Permutations[] =
            {
                std::make_tuple(0,      0,  0)
                , std::make_tuple(0,    0,  1)
                , std::make_tuple(0,    1,  0)
                , std::make_tuple(0,    1,  1)
                , std::make_tuple(1,    0,  0)
                , std::make_tuple(1,    2,  3)
                , std::make_tuple(1,    1,  0)
                , std::make_tuple(1,    1,  1)
                // ...
            };
        
            boost::for_each(Permutations, [](const Tuple& constants) { Factor(constants)->foo(42.0); });
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2018-08-22
          • 2020-12-21
          • 2020-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多