Specifying one type for all arguments passed to variadic function or variadic template function w/out using array, vector, structs, etc?

27,121

Solution 1

You can just accept the arguments by the variadic template and let typechecking check the validity later on when they are converted.

You can check convertibility on the function interface level though, to make use of overload resolution for rejecting outright wrong arguments for example, by using SFINAE

template<typename R, typename...> struct fst { typedef R type; };

template<typename ...Args>
typename fst<void, 
  typename enable_if<
    is_convertible<Args, ToType>::value
  >::type...
>::type 
f(Args...);

For your use-case if you know the steps to go from an std::array<> to your dragon_list_t then you have already solved it though according to the first option above ("convert-later"):

template<typename ...Items>
dragon_list_t make_dragon_list(Items... maidens) {
    std::array<Maiden, sizeof...(Items)> arr = {{ maidens ... }};
    // here be dragons
}

If you combine this with the above is_convertible approach you have a reject-early template that also does overload resolution on arguments and rejects them if not applicable.

Solution 2

If you don't use template on the parameter not in the pack the variadic function will resolve to have all arguments of the same type.

Here's an example for an extended max function that only accepts ints (or types convertible to int).

int maximum(int n) // last argument must be an `int`
{
    return n;
}

template<typename... Args>
int maximum(int n, Args... args) // first argument must be an int
{
    return std::max(n, maximum(args...));
}

Explanation: When you unpack the argument pack (args...) the compiler looks for the best overload. If the pack had only one parameter then the best candidate is maximum(int) so the only parameter must be and of type int (or convertible to int). If there are more than one elements in the pack then the only candidate is maximum(int, typename...) so the first argument must be of type int (or convertible to int). It's simple to prove by induction that all the types in the pack must be of a type convertible to int.

Solution 3

Since you've included the C++0x tag, the obvious answer would be to look up initializer lists. An initializer list lets you specify a number of arguments to a ctor that will be automatically converted to a single data structure for processing by the ctor.

Their primary (exclusive?) use is for exactly the sort of situation you've mentioned, passing a number of arguments of the same type to use in creating some sort of list/array/other collection of objects. It'll be supported by (for one example) std::vector, so you could use something like:

std::vector<dragon> dragons_to_slay{Eunice, Helga, Aida};

to create a vector of three dragon objects. Most (all?) of the other collections will include the same, so if you really insist on a list of dragons you should be able to get that pretty easily as well.

Solution 4

A recent proposal, Homogeneous variadic functions, addresses this by making something like your first construct legal. Except of course to use the parameter pack you will have to name it. Also the exact syntax doesn't seem very concrete yet.

So, under the proposal this will actually be legal (you can see a similar construct in the paragraph "The template introducer" in the paper):

dragon_list_t make_dragon_list(Maiden... maidens) {
    //here be dragons
}

Solution 5

using c++17, you can write

template <class T, class... Ts, class = std::enable_if_t<(std::is_same_v<T, Ts> && ...)>
void fun(T x, Ts... xs)
{
}
Share:
27,121
Brett Rossier
Author by

Brett Rossier

Updated on July 09, 2022

Comments

  • Brett Rossier
    Brett Rossier almost 2 years

    This question is about guaranteeing all arguments are of the same type while exhibiting a reject-early behavior with a clean compiler error, not a template-gibberish error

    I'm creating a function (possibly member function, not that it matters... maybe it does?) that needs to accept an unknown number of arguments, but I want all of them to be the same type. I know I could pass in an array or vector, but I want to be able to accept the list of args directly without extra structure or even extra brackets. It doesn't look like variadic functions by themselves are typesafe, and I wasn't sure how to go about this w/ variadic template functions. Here's essentially what I'm aiming for (more than likely not correct code, and totally not for the purpose of getting lists of dragons, lol):

    //typedef for dragon_list_t up here somewhere.
    
    enum Maiden {
        Eunice
        , Beatrice
        , Una_Brow
        , Helga
        , Aida
    };
    
    dragon_list_t make_dragon_list(Maiden...) {
        //here be dragons
    }
    

    OR

    template<Maiden... Maidens> dragon_list_t make_dragon_list(Maidens...) {
        //here be dragons
    }
    

    USAGE

    dragon_list_t dragons_to_slay
        = make_dragon_list(Maiden.Eunice, Maiden.Helga, Maiden.Aida)
    ;
    

    Tried a few things similar to the above already, no dice. Suggestions? Obvious oversights I may have made? I know it may not be a huge deal to do this instead:

    dragon_list_t make_dragon_list(std::array<Maiden> maidens) {
        //here be dragons.
    }
    dragon_list_t dragons_to_slay
        = make_dragon_list({Maiden.Eunice, Maiden.Helga, Maiden.Aida})
    ;
    

    but I'd much rather be able to do it the first way if possible.

  • Todd Gardner
    Todd Gardner over 13 years
    Err, and by typesafe, I mean, as typesafe as the underlying type, which for a non-class enum isn't very much.
  • Potatoswatter
    Potatoswatter over 13 years
    +1 for giving OP exactly what he asked for, although it's for better or worse
  • Todd Gardner
    Todd Gardner over 13 years
    I haven't played around with the variadic templates enough to know if the early convertible is called for, but +1 the std::array conversion, didn't think of that.
  • Todd Gardner
    Todd Gardner over 13 years
    Hmm, I think the reject-early template isn't that good for general case. If Dragon was a base class, then your first argument (or all your arguments), may be a derived class, and therefor not convertible to each other. When dragon is an enum, it could be the same thing if your first class is convertible to integer type but not an integer type itself. I think relying on overloading is more extensible.
  • Johannes Schaub - litb
    Johannes Schaub - litb over 13 years
    @Todd the reject-early template checks only convertibility of the arguments to ToType (Dragon), not of the arguments to each other. So D1->B is checked and D2->B too, but D1->D2 is not checked.
  • Puppy
    Puppy over 13 years
    You can compile-time bitshift, that is, enum { first_value = 1, second_value = 1 << 1, third_value = 1 << 2 };
  • Potatoswatter
    Potatoswatter over 13 years
    @DeadMG: I'd write it that way, but you'd be surprised how many readers have never seen that operator before.
  • Brett Rossier
    Brett Rossier over 13 years
    Didn't even think to look at init lists, thanks for the suggestion. Still chewing on all these answers :\
  • Brett Rossier
    Brett Rossier over 13 years
    I have, but out of curiosity, would there be any concerns about bit-endianness? I know that's probably obscure. I don't know what CPUs that would be an issue with, and it's not like I'm trying to build something that's 100% cross-platform or anything. Just curious.
  • Puppy
    Puppy over 13 years
    Well, since you don't care which bit is set, only that each flag corresponds to one bit, then there's no reason that endianness or portability should break the code. As long as you don't try to set more bits than exist in the backing type, you're fine.
  • Potatoswatter
    Potatoswatter over 13 years
    @pheadbaq: No, a bitset encoding is just a number like any other, so (Eunice+Beatrice+Helga) = 1+2+8 = 11 is no more endianness-sensitive than simply writing the number 11.
  • Brett Rossier
    Brett Rossier over 13 years
    Interesting... can't say I understand why this works, any info/links on that?
  • Brett Rossier
    Brett Rossier over 13 years
    Out of curiosity, if the convert-later option were implemented in a library that another dev was using, what kind of error would they see if they didn't have the implementation for make_dragon_list, just a header, and they fed it the wrong types? Would that not even be a valid concern, or would it be a reason to favor the reject-early option?
  • Johannes Schaub - litb
    Johannes Schaub - litb over 13 years
    @pheadbaq i have no idea. It really depends on the very code within the template. But it won't be nice i think
  • Noein
    Noein over 6 years
    Concepts that made it into C++2a (so far) don't include this. See here.
  • Gukki5
    Gukki5 over 4 years
    can't understand why this doesn't already exist in the language! i want this all of the time.
  • Mike Kaganski
    Mike Kaganski over 3 years
  • Mike Kaganski
    Mike Kaganski over 3 years
    The github issue only lists the final vote numbers, no rationales; but maybe because of issues like possible ambiguity with C-style variadic functions? E.g., you can't declare such a homogenous variadic function without the pack name, as common in forward declarations...
  • Tony Delroy
    Tony Delroy about 3 years
    @BrettRossier asked a long time ago, but for anyone wondering an example may help: maximum(A, B, C) is evaluated as std::max(A, maximum(B, C)), in turn evaluated as std::max(A, std::max(B, maximum(C))): during the expansion first A and later B (and in general all but the last value) end up being the first argument to distinct calls to the variadic form of maximum, so they're passed to the int n argument, whereas C ends up passed to maximum(int n). So, all arguments must be ints.
  • Nuclear
    Nuclear over 2 years
    Move-only types cannot be passed via std::initializer_list, at least, not without additional hacks. It also requires an extra set of brackets, for the initializer_list. It would be nice to be able to specify a variadic template with parameter of the same type