cppuser1
cppuser1

Reputation: 31

Why does typedef not offer protection in function parameters?

I was under the impression that a good use-case for typedef was to insure that the wrong type of argument was not passed to a function. But that doesn't seem to actually be enforced by the compiler.

Can someone tell me why the below compiles? And how I can achieve my goal of having a function take MyType and the compiler complaining if I try to pass YourType?

#include <iostream>
#include <string>

typedef std::string MyType;
typedef std::string YourType;

void PrintMyString(const MyType& my_type) {
  std::cout << my_type;
}

int main()
{
    MyType my_type = "Hello";
    YourType your_type = " World";
    PrintMyString(my_type);
    PrintMyString(your_type); // should fail?
}

Upvotes: 3

Views: 70

Answers (3)

Ami Tavory
Ami Tavory

Reputation: 76297

This problem, of phantom types, comes up occaisonally:

I think the way to go is with something like this:

struct typedef_0 : public specific_type
{
// Add variadic perfect-forwarding ctor here.
};

This would create a type typedef_0 that is "nearly interchangeable" with specific_type. If you wanted another one, you would call it some other thing, e.g., typedef_1.

You could use this to create a macro that achieves "strong" typedefness. Something like:

 #define MAKE_STRONG_TYPEDEF(ORIG_TYPE, NEW_TYPE) \
 struct NEW_TYPE : public ORIG_TYPE \
 { \
 template<typename ...T>NEW_TYPE(T &&..t) : \
     ORIG_TYPE(std::forward(T...)(t)){}
 };

(Didn't try to compile it, but that's the general idea.)

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40859

Because typedef creates an alias, not a new type. For that you need some sort of "strong typedef". Boost has one.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180510

typedefs are just an alias to a type, it does not make a new type. If both typedefs alias the same type then you can interchange them.

It looks like you can use a strong typedef or you could wrap the type in a wrapper class and use the wrapper class as the function parameter.

Upvotes: 2

Related Questions