[Tex/LaTex] Passing nodes as parameters to a macro in TikZ

macrosparameterstikz-pgf

I would like to define a macro which would take two nodes as arguments and
"connect" them using a third, predefined node. Like this:

\documentclass{minimal}

\usepackage{tikz}
\usetikzlibrary{shapes,positioning,fit}

\newcommand{\diamondconn}[3]{
  \node[diamond, draw, innter sep=2pt] (diamond) { #1 };
  % get the references to #2 and #3 and position them
  % on the left and right side of the `conn' node
}

\begin{document}

% instead of writing this...
\begin{tikzpicture}
  \node[diamond, draw, inner sep=2pt] (diamond) { conn };
  \node[draw, left=0pt of diamond.west] { foo };
  \node[draw, circle, right=0pt of diamond.east] { bar };
\end{tikzpicture}

% I would like to write this:
\begin{tikzpicture}
  \diamondconn{conn}{
    \node[draw, rectangle] { foo };
  }{
    \node[draw, circle] { bar };
  }
\end{tikzpicture}

\end{document}

I know I could do it backwards, i.e. define a macro for the connecting node
and insert it when needed, I am just curious if the first option is possible
as well.

Best Answer

I assume you want to keep the node definitions you pass as arguments independent of what happens inside the macro (so you don't want to explicitly use left of=diamond.west in the node definition). In order to achieve this, you can wrap the nodes passed in scope environments inside the macro and "inject" the positioning options, or, as Martin Scharrer suggests, use \tikzset inside curly braces to set the options locally:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes,positioning,fit}

\newcommand{\diamondconn}[3]{

  \node[diamond, draw, inner sep=2pt] (diamond) { #1 };
  {\tikzset{every node/.style={left=0pt of diamond.west}} #2 }
  {\tikzset{every node/.style={right=0pt of diamond.east}} #3 } 
}

\begin{document}

\begin{tikzpicture}
  \diamondconn{conn}{
    \node[draw, rectangle] { foo };
  }{
    \node[draw, circle] { bar };
  }
\end{tikzpicture}

\end{document}