logo
down
shadow

Variadic templates in C++ 11 and class constructors


Variadic templates in C++ 11 and class constructors

By : Kanishka
Date : October 23 2020, 06:10 PM
Hope that helps You can't have a variadic number of fields d_x1, d_x2, ...; but that can be worked around by using std::tuple:
code :
#include <memory>
#include <tuple>

template< typename T, typename... XS >
class MyClass
{
    std::shared_ptr<T> d_track;
    std::tuple<std::shared_ptr<XS>...> d_xs;
public:

    MyClass( std::shared_ptr< T > track ,
             std::shared_ptr< XS >... xs ) ;
};

template< typename T, typename... XS >
MyClass< T, XS... >::MyClass( std::shared_ptr< T > track ,
                              std::shared_ptr< XS >... xs)
    : d_track( track ) , d_xs( xs... )
{
}


Share : facebook icon twitter icon
For constructors, how do I choose between variadic-templates vs std::initializer_list?

For constructors, how do I choose between variadic-templates vs std::initializer_list?


By : Andrew
Date : March 29 2020, 07:55 AM
around this issue A variadic template allows you providing arguments of different types, while an std::initializer_list is templated with the type of the argument. This means the type of all the elements in the list must be the same (or convertible to the underlying type, but no narrowing conversions are allowed). Depending on whether or not this is desirable for you, you may choose one or the other.
Also, a variadic template is usually the default choice if you need perfect forwarding, in that the syntactic form T&& can bind to both lvalue references and rvalue references, while a similar type deduction cannot be performed for initializer_list:
code :
struct A
{
    // Deduces T& for lvalue references, T for rvalue references, and binds to both
    template<typename... Ts>
    A(Ts&&...) { }

    // This is an rvalue reference to an initializer_list. The above type deduction
    // does not apply here
    template<typename T>
    A(initializer_list<T>&&) { }
};
struct A
{
    A(int i) { }
};

struct B
{
    B(int) { }
    B(std::initializer_list<A>) { }
};

int main()
{
    B b {1}; // Will invoke the constructor accepting initializer_list
}
Acceptable way to restrict variadic templates in constructors

Acceptable way to restrict variadic templates in constructors


By : Tianyaa Lee
Date : March 29 2020, 07:55 AM
should help you out Overload resolution doesn't consider accessibility; that check is done later.
What you are doing is not actually SFINAE; it is not affecting overload resolution, only making the instantiation of the template constructor ill-formed after it's selected by overload resolution.
code :
template< class T >
class myobject
{
    /* ... */
public:

    /* ... */
    myobject( const char * ptr )
    {
        std::cout << "const char * constructor" << std::endl;
    }

    template< typename... Ts >
    myobject( Ts... params )
    : myobject( typename CheckVaradicArgs<Ts...>::type(), params... )
    {
        std::cout << "Ts constructor with " << sizeof...(params) << std::endl;
    }

};

char * p = nullptr;
myobject<int> something(p);
template< class T >
class myobject
{

    template< typename... Ts >
    using CheckVariadicArgs =
            typename std::enable_if< 
                all_true< std::is_convertible<Ts, T>... >::value, int
                >::type;
public:

    myobject( const myobject& other )
    {
        std::cout << "Copy constructor" << std::endl;
    }

    template< typename... Ts, CheckVariadicArgs<Ts...>* = nullptr >
    myobject( Ts... params )
    {
        std::cout << "Ts constructor with " << sizeof...(params) << std::endl;
    }

};
Deduction guides and variadic class templates with variadic template constructors - mismatched argument pack lengths

Deduction guides and variadic class templates with variadic template constructors - mismatched argument pack lengths


By : mayyuval
Date : March 29 2020, 07:55 AM
I hope this helps . To simplify your example further, it appears that GCC does not implement variadic template arguments in deduction guides:
https://wandbox.org/permlink/4YsacnW9wYcoceDH
Reusing variadic templates for constructors

Reusing variadic templates for constructors


By : Epharos
Date : March 29 2020, 07:55 AM
To fix the issue you can do How can one store a variadic template to enable reuse in later instances? , You can acheive this by storing the arguments in a tuple:
code :
#include <vector>
#include <tuple>

template<typename T, int index, typename ...initArgs>
struct VectorInit {
  static void append(std::vector<T> & dst, 
                     std::tuple<initArgs...> const& args) {
    VectorInit<T, index-1, initArgs...>::append(dst, args);
    dst.emplace_back(std::get<index>(args));
  }
};

template<typename T, typename ...initArgs>
struct VectorInit<T, 0, initArgs...> {
  static void append(std::vector<T> & dst, 
                     std::tuple<initArgs...> const& args) {
    dst.emplace_back(std::get<0>(args));
  }
};

template <typename T, typename ...initArgs>
class Collection_class {
   std::vector<T> storage; 
   std::tuple<initArgs...> init_args;

public:
   Collection_class(initArgs... args)
     : init_args(args...) {
   }

   void CreateInstance() {
     storage.reserve(sizeof...(initArgs));
     VectorInit<T, sizeof...(initArgs)-1, initArgs...>::append(storage, init_args);
   }
};

int main() {
    Collection_class<double, float, int> test(1.2f, 4);
    test.CreateInstance();
}
Combination of 2 templated constructors for class build with variadic templates. How?

Combination of 2 templated constructors for class build with variadic templates. How?


By : user3044629
Date : March 29 2020, 07:55 AM
I hope this helps . I created some small factory class. See the code below. The factory uses a simple map with a key and a class creator function. The challenge was that I wanted to use different signatures for the createInstance functions. With that, I could use different derived classes with different constructor signatures. So, I would be able to pass different values to the constructor of the classes. , How about simply removing the constructor taking the std::function?
code :
template<typename Function>
Creator(Function&& fun) : m_any(std::function(fun)) {}
template <typename ... Args>
using Func = std::add_pointer_t<Ret(Args...)>;

// in you class:

template<typename Function, std::enable_if_t<std::is_pointer_v<Function>, int> = 0>
Creator(Function fun) : m_any(fun) {}
template<typename T>
concept FunctionPointer = requires(T t) {
    requires std::is_pointer_v<T>;
    requires std::is_function_v<std::remove_pointer_t<T>>;
    { std::function(t) };
};

// then in your class:

Creator(FunctionPointer auto fun) : m_any(fun) {}
Related Posts Related Posts :
  • What's wrong with these pointer initialization
  • Access Violation Using memcpy or Assignment to an Array in a Struct
  • Wrong operator() overload called
  • Subtractively sweep a solid through another in python (or C++)
  • boost ublas: rotate 2d vector
  • How can a Windows program temporarily change its time zone?
  • small & readable scheme interpreter in C++?
  • Cannot change the height of a combo box in the VS Dialog Editor
  • Access reading error when using class member variable
  • How to tell if two exe's are the same code-wise?
  • Modifying an old Windows program not to call exit after a keypress without source access
  • What is name lookup mechanism?
  • What does the C++ compiler error "looks like a function definition, but there is no parameter list;" mean?
  • Why does this crash with access violation to 0xcccccc...?
  • How to find out how namespace got polluted?
  • What is the _REENTRANT flag?
  • Managing many objects at once
  • How to create ActiveX DLL in Visual C++
  • Generic allocator class without variadic templates?
  • Comparation in JNI
  • Using a function with reference as a function with pointers?
  • How to initialize an unsigned long long type?
  • How to practically customize IE context menu?
  • Trying to Create a ToolBar with an ImageList, not working
  • How does the destructor know when to activate itself? Can it be relied upon?
  • Conway's Game of Life - C++ and Qt
  • Accessing any structs members at run-time
  • Including #includes in header file vs source file
  • How does switch compile in Visual C++ and how optimized and fast is it?
  • How to override nested C++ objects methods?
  • penalty for "inlined" classes
  • C++ Library for implementing a web services api over legacy code?
  • C++-Singleton class
  • Floating point precision in Visual C++
  • Compiler error when overriding virtual methods
  • What is the point of function pointers?
  • Which is faster in memory, ints or chars? And file-mapping or chunk reading?
  • ISO file in C++
  • Expected Class-name before { token
  • Can I trust floats or doubles representing integers to retain precision?
  • Qt execute multiple get with QNetworkAccessManager
  • Big and Little endian question
  • Visual Studio 2008 compiles anything in C++ file?
  • C++ pointer to functions, Beginner Question
  • Fastest algorithm for primality test
  • Passing array of pointers to another class
  • Handling macro redefinition without modifying .h files ... C / C++ language
  • Implement SSL with SSPI: How to start?
  • Creating a simple VS2008 visualizer inside autoexp.dat (problem with casting)
  • C++ - Unicode Newline
  • Program crashing with 'std::out_of_range' error
  • Use signed or unsigned char in constructing CString?
  • Parallel execution policies in C++ 17
  • C++ Class Templates (Queue of a class)
  • Convert image into useable byte array in C?
  • pointer to preallocated memory as an input parameter and have the function fill it
  • Animated Image in Win32
  • error on compiling statically linked library created in Qt
  • How to easily pass a very long string to a worker process under Windows?
  • Can a class add friend classes at runtime in C++?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk